Paul's JavaScript Examples    
 
Convert Kilometers to Miles and vice versa

Convertor script to convert kilometers to miles and miles to kilometers. Just fill in one value and click on the Convert button. use the Clear button to clear the values. Note, negative values are not supported.

Example

Distances
Kilometers
Miles
  

Usage

<INPUT TYPE="button" VALUE="Convert" onClick=computeDistForm(this.form)>
<INPUT TYPE="button" VALUE="Clear" onClick=clearDistForm(this.form)>

Source

<SCRIPT LANGUAGE="javascript">
<!--
function checkNumber(numStr, fieldName)
{
	msg = fieldName + " field has invalid data: " + numStr.value;
	str = numStr.value;
	for (var i=0; i < str.length; i++)
	{
		var ch = str.substring(i,i+1);
		if ( (ch < "0" || ch > "9") && ch != '.' )
		{
			alert(msg);
			return false;
		}
	}
	return true;
}

function computeDistForm(distform)
{
	// if both forms empty - error
	if ( (distform.km.value == null || 
            distform.km.value.length == 0) &&
           (distform.mile.value == null ||
            distform.mile.value.length == 0) )
	{
		alert("Both fields empty.");
		return;
	}

	// if both forms filled error
	if ( (distform.km.value != null &&
		distform.km.value.length > 0) &&
		(distform.mile.value != null &&
		 distform.mile.value.length > 0) )
	{
		alert("Error: both fields have data.");
		return;
	}

	// calculate kilometers
	if ( (distform.km.value == null ||
		distform.km.value.length == 0) &&
		(distform.mile.value != null &&
		 distform.mile.value.length > 0) )
      {
		if (checkNumber(distform.mile,"Miles"))
		{
			distform.km.value = (distform.mile.value * 1.60934);
		}

	}

	// calculate miles
	if ( (distform.km.value != null &&
	      distform.km.value.length > 0) &&
		(distform.mile.value == null ||
	    	 distform.mile.value.length == 0) )
	{
		if (checkNumber(distform.km,"Kilometers"))
		{
			distform.mile.value = (distform.km.value / 1.60934);
		}		
	}
}

// used for distance conversion
function clearDistForm(distform)
{
        distform.mile.value="";
	distform.km.value="";
}

// -->
</SCRIPT>